import { PlusOutlined } from '@ant-design/icons';
import {
  ActionType,
  BetaSchemaForm,
  ProColumns,
  ProFormColumnsType,
  ProTable,
} from '@ant-design/pro-components';
import { useStateData } from '@jeoshi-design/rex-design.hooks.core';
import Editor from '@monaco-editor/react';
import { request } from '@umijs/max';
import { Button, Modal } from 'antd';
import { useRef } from 'react';

const Mock = () => {
  const { state, update } = useStateData(() => ({
    open: false,
    title: '新增',
    initValues: {} as Record<string, unknown>,
  }));

  const actionRef = useRef<ActionType>();
  const columns: ProColumns[] = [
    {
      dataIndex: 'id',
      title: 'id',
      hideInSearch: true,
      hideInForm: true,
      width: 50,
    },
    {
      dataIndex: 'pathName',
      title: '路径',
      width: 150,
      formItemProps: {
        rules: [{ required: true }],
      },
    },
    {
      dataIndex: 'content',
      title: 'mock数据',
      hideInSearch: true,
      ellipsis: {
        showTitle: false,
      },
      formItemProps: {
        rules: [
          { required: true },
          {
            validator(rule, value, callback) {
              try {
                if (!Number.isNaN(+value)) {
                  throw new Error('');
                }
                if (value) {
                  JSON.parse(value);
                }
                callback();
              } catch (error) {
                callback('请输入合法的 JSON 数据');
              }
            },
          },
        ],
      },
      renderFormItem: () => {
        return <Editor defaultLanguage="json" height={400} />;
      },
    },
    {
      dataIndex: 'createdAt',
      title: '创建时间',
      hideInSearch: true,
      hideInForm: true,
      valueType: 'dateTime',
      width: 150,
    },
    {
      dataIndex: 'action',
      title: '操作',
      width: 150,
      hideInSearch: true,
      hideInForm: true,
      render: (_, record) => {
        return (
          <>
            <Button
              type="link"
              size="small"
              onClick={() => {
                state.open = true;
                state.initValues = record;
                update();
              }}
            >
              修改
            </Button>
            <Button
              type="link"
              size="small"
              danger
              onClick={() => {
                Modal.confirm({
                  title: '删除吗',
                  onOk: async () => {
                    await request(`/api/mock/${record.id}`, {
                      method: 'delete',
                    });

                    actionRef.current?.reset?.();
                  },
                });
              }}
            >
              删除
            </Button>
          </>
        );
      },
    },
  ];

  return (
    <ProTable
      columns={columns as ProColumns[]}
      actionRef={actionRef}
      cardBordered
      request={async (params) => {
        const res = await request('/api/mock', {
          params,
        });
        return res.data;
      }}
      rowKey="id"
      search={{
        labelWidth: 'auto',
      }}
      form={{}}
      toolBarRender={(action) => [
        <Button
          key="button"
          icon={<PlusOutlined />}
          onClick={() => {
            state.open = true;
            state.initValues = {};
            update();
          }}
          type="primary"
        >
          新建
        </Button>,
        <Modal
          key="ModalForm"
          open={state.open}
          title={state.title}
          destroyOnClose
          width={800}
          onCancel={() => {
            state.open = false;
            update();
          }}
          footer={null}
        >
          <BetaSchemaForm
            columns={columns as ProFormColumnsType[]}
            layout="horizontal"
            initialValues={state.initValues}
            onFinish={async (values) => {
              await request(
                '/api/mock' +
                  (state.initValues.id ? `/${state.initValues.id}` : ''),
                {
                  data: values,
                  method: state.initValues.id ? 'patch' : 'post',
                },
              );

              action?.reset?.();
              state.open = false;
              update();
            }}
            submitter={{
              render(props, dom) {
                return (
                  <div
                    style={{
                      display: 'flex',
                      justifyContent: 'flex-end',
                      gap: 8,
                    }}
                  >
                    <Button
                      onClick={() => {
                        state.open = false;
                        update();
                      }}
                    >
                      取消
                    </Button>
                    {dom}
                  </div>
                );
              },
            }}
          />
        </Modal>,
      ]}
    />
  );
};

export default Mock;
